/**
 * @ngdoc overview
 * @name diary.services
 * @description
 *   工作日志模块服务
 */

angular.module('diary.services', [])

.constant('SCHEDULE', [
  { value: '0', percent: '0%' },
  { value: '1', percent: '10%' },
  { value: '2', percent: '20%' },
  { value: '3', percent: '30%' },
  { value: '4', percent: '40%' },
  { value: '5', percent: '50%' },
  { value: '6', percent: '60%' },
  { value: '7', percent: '70%' },
  { value: '8', percent: '80%' },
  { value: '9', percent: '90%' },
  { value: '10', percent: '100%' }
])

/**
 * @ngdoc service
 * @name diary.services.Diary
 * @description
 *   日志通用服务
 */
.factory('Diary', function($http, Settings) {
  var getModuleUrl = function () {
    return Settings.rootUrl + '/diary';
  }

  function create(data) {
    return $http.post(getModuleUrl() + '/save', data)
  }

  function remove(id) {
    return $http.post(getModuleUrl() + '/del', {
      diaryids: id
    });
  }

  function get(id) {
    return $http.get(getModuleUrl() + '/show', {
      params: { id: id }
    })
  }

  function update(data) {
    return $http.post(getModuleUrl() + '/update', data)
  }

  return {
    create: create,
    get: get,
    update: update,
    remove: remove,

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#addComment
     * @methodOf  diary.services.Diary
     * @param     {Object}   data    表单数据
     *
     * @description
     *   新增一条日志评论
     *
     * - `diaryid` ：     日志ID
     * - `content` ：     内容，可带html标签
     * - `uid` ：         评论者UID
     * - `tocid` ：       被回复的评论的ID
     * - `touid` ：       被回复的评论的作者的UID
     * - `from` ：        客户端类型，0：网站；1：手机网页版；2：android；3：iphone
     * - `commentcount` ：该评论回复数，默认0
     *
     * @returns   {Object}  $q.defer.promise
     */
    addComment: function(data) {
      data = angular.extend({
        from: 1
      }, data);

      return $http.post(getModuleUrl() + '/addComment', data);
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#index
     * @methodOf  diary.services.Diary
     * @param     {Object}   params    请求参数
     * @description
     *   获取我的日志列表
     *
     * @returns   {HttpPromise}   HttpPromise
     */
    mine: function(params){
      return $http.get(getModuleUrl(), { params: params });
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#allsubs
     * @methodOf  diary.services.Diary
     * @param     {Object}   params    请求参数
     * @description
     *   获取下属日志列表
     *   
     * @returns   {HttpPromise}   HttpPromise
     */
    allsubs: function(params){
      return $http.get(getModuleUrl() + '/allsubs', { params: params });
    },


    /**
     * @ngdoc     method
     * @name      diary.services.Diary#other
     * @methodOf  diary.services.Diary
     * @param     {Object}   params    请求参数
     * @description
     *   获取其他日志列表
     *   
     * @returns   {HttpPromise}   HttpPromise
     */
    other: function(params){
      return $http.get(getModuleUrl() + '/other', { params: params });
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#show
     * @methodOf  diary.services.Diary
     * @param     {String}   id    日志id
     * @description
     *   获取单条日志数据
     *   
     * @returns   {HttpPromise}   HttpPromise
     */
    show: function(id){
      return $http.get(getModuleUrl() + '/show', { params: { id : id } })
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#add
     * @methodOf  diary.services.Diary
     * @param     {String}   diaryDate    格式为'yyyy-MM-dd'的日期
     *
     * @description
     *   获取指定日期的原计划数据
     */
    add: function(diaryDate){
      return $http.get(getModuleUrl() + '/add' + (diaryDate ? '&diaryDate=' + diaryDate: ''));
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#edit
     * @methodOf  diary.services.Diary
     * @param     {String}   id    日志 id
     *
     * @description
     *   获取指定日志的编辑数据
     */
    edit: function(id) {
      return $http.get(getModuleUrl() + '/edit&diaryid=' + id);
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#personal
     * @methodOf  diary.services.Diary
     * @param     {Object}   params    请求参数
     *
     * @description
     *  查看某人日志
     */
    personal: function(params){
      return $http.get(getModuleUrl() + '/personal',{ params: params });
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#attention
     * @methodOf  diary.services.Diary
     * @param     {String}   auid    用户 id
     *
     * @description
     *  关注用户
     */
    attention: function(auid){
      return $http.get(getModuleUrl() + '/attention',{params: { auid : auid}})
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#unattention
     * @methodOf  diary.services.Diary
     * @param     {String}   auid    用户 id
     *
     * @description
     *  取消关注用户
     */
    unattention: function(auid){
      return $http.get(getModuleUrl() + '/unattention',{ params: { auid : auid}})
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#planfromschedule
     * @methodOf  diary.services.Diary
     * @param     {String}   todayDate    格式为'yyyy-MM-dd'的日期
     *
     * @description
     *   获取指定日期的日程事件列表
     */
    planfromschedule: function(todayDate){
      return $http.get(getModuleUrl() + '/planfromschedule',{ params: { todayDate : todayDate }})
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#setting
     * @methodOf  diary.services.Diary
     *
     * @description
     *   获取个人设置数据
     */
    setting: function(){
      return $http.get(getModuleUrl() + '/setting')
    },

    /**
     * @ngdoc     method
     * @name      diary.services.Diary#savesetting
     * @methodOf  diary.services.Diary
     * @param     {Object}   data    表单数据
     *
     * @description
     *   保存个人设置
     */
    savesetting: function(data){
      return $http.post(getModuleUrl() + '/savesetting', data)
    }
  };
})

/**
 * @ngdoc service
 * @name diary.services.DiaryUtils
 * @description
 *   日志模块工具函数集
 */
.factory('DiaryUtils', function($filter, $ionicPopup, $timeout, $state, dateFilter, IbPopup, User) {

  return {
    // 处理提交的表单
    handleFormData: function(data) {
      return angular.extend({}, data, {
        plantime: $filter('date')(data.plantime, 'yyyy-MM-dd'),
        shareuid: User.addPrefix(data.shareuid)
      })
    },

    //设置时间提醒
    setRemind: function($scope, plan){
      $scope.remindConf = {
        start: $scope.workStart.start,
        continueTime: 0.5,
        getStartHours: function() {
          var ret = [];
          for(var i = $scope.workStart.start; i < $scope.workStart.end; i += 0.5) {
            ret.push(i);
          }
          return ret;
        },
        getContinueTimes: function() {
          var ret = [];
          for(var i = 0.5; i <= $scope.workStart.end - this.start; i += 0.5) {
            ret.push(i);
          }
          return ret;
        }
      };

      function popupContinueTime(plan){
        $ionicPopup.show({
          template: '<select class="col" ng-model="remindConf.continueTime" ng-options="(\'持续 \' + item + \' 小时\') for item in remindConf.getContinueTimes() track by item"></select>',
          title: '持续时间',
          scope: $scope,
          buttons: [{
            text: '取消'
          }, {
            text: '确认',
            type: 'button-positive',
            onTap: function(ok) {
              if(ok) {
                plan.timeremind = $scope.remindConf.start + ',' + ($scope.remindConf.start + +$scope.remindConf.continueTime);
              }
            }
          }]
        })
      }

      $ionicPopup.show({
        template: '<select class="col" ng-model="remindConf.start" ng-options="(item|numToHHmm) for item in remindConf.getStartHours() track by item"></select>',
        title: '开始时间',
        scope: $scope,
        buttons: [{
          text: '取消'
        }, {
          text: '确认',
          type: 'button-positive',
          onTap: function(ok) {
            if(ok) {
              $timeout(function(){
                popupContinueTime(plan);
              }, 0);
            }
          }
        }]
      });
    },

    //取消时间提醒
    delRemind: function(plan){
      plan.timeremind = '';
    },

    //选择开始日期
    selectedStartDate: function($scope){
      $ionicPopup.show({
        template: '<div class="diary-select">' +
          '<input type="date" class="diary-item" ng-model="formData.startDate"  data-tap-disabled ="true" required >' +
          '</div>',
        title: '选择日期',
        scope: $scope,
        buttons: [{
          text: '取消'
        }, {
          text: '确认',
          type: 'button-positive',
          onTap: function(e) {
            var startDate = $scope.formData.startDate,
              today = new Date;

            if (!startDate) return;

            $timeout(function() {
              if (startDate > today) {
                IbPopup.alert({
                  title: '抱歉，选中的日期没有日志且没有新建权限！'
                })
              } else {
                $scope.formData.originalPlan = '';
                $scope.formData.todayDate = dateFilter(startDate, 'yyyy-MM-dd');
                $scope.todayWeekday = dateFilter(startDate, 'EEEE')
              }
            }, 0);
            return true;
          }
        }]
      })
    },

    //选择结束日期
    selectedEndDate: function($scope){
      $ionicPopup.show({
        template: '<div class="diary-select">' +
          '<input type="date" class="diary-item" ng-model="formData.endDate"  data-tap-disabled ="true" required >' +
          '</div>' +
          '<div>' + '{{date}}' + '<div>',
        title: '选择日期',
        scope: $scope,
        buttons: [{
          text: '取消'
        }, {
          text: '确认',
          type: 'button-positive',
          onTap: function(e) {
            var endDate = Date.parse(new Date($scope.formData.endDate));
            if (!endDate) return;
            $scope.formData.plantime = dateFilter(endDate, 'yyyy-MM-dd');
            $scope.tomorrowWeekday = dateFilter(endDate, 'EEEE')
          }
        }]
      })
    }

  }

})



